package http.proxy;

import http.executor.Executor;
import http.executor.ResponseExecutor;
import http.mapping.DefaultHandlerMapping;
import http.mapping.HandlerMapper;
import http.util.FullHttpResponseUtil;
import http.util.IdGenerator;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.util.CharsetUtil;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 请求拦截器，用于分发路由
 */
@Component
public class DispatcherInterceptor implements MethodInterceptor {

    @Autowired
    private DefaultHandlerMapping defaultHandlerMapping;

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        if("channelRead".equals(method.getName()) ){
            System.out.println("执行前...method:"+method);
            ChannelHandlerContext ctx= (ChannelHandlerContext) args[0];
            FullHttpRequest req= (FullHttpRequest) args[1];

            if ("/favicon.ico".equals(req.uri())) {
                FullHttpResponseUtil.response(HttpResponseStatus.OK,"favicon.ico",ctx);
                return null;
            }
            Object object = proxy.invokeSuper(obj, args);
            String id = IdGenerator.timestamp();
            boolean isPut = Executor.put(id,defaultHandlerMapping.getHandler(req,ctx));
            if(isPut){
                ResponseExecutor.putChannelHandlerContext(id, ctx);
            }else{
                FullHttpResponseUtil.response(HttpResponseStatus.NOT_FOUND,"no handler found",ctx);
            }
            System.out.println("执行后...");
            return  object;
        }else{
            Object object = proxy.invokeSuper(obj, args);
            return  object;
        }
    }

    private boolean paramIsMatcher(Method method){
        for (Class clazz : method.getParameterTypes()) {
            if(clazz.equals(FullHttpRequest.class)){
                return true;
            }
        }
        return false;
    }



}
